import { Text, View, StyleSheet, Image, TextInput, ActivityIndicator, TouchableOpacity } from 'react-native'
import React, { useState } from 'react'
import { connect } from 'react-redux'
import { pTx } from "../../utils/dimensions"
import { asyncLogin, setIsLogin } from "../../redux/features/appSlice"
import { ethers } from "ethers";
import { Toast } from '@ant-design/react-native'
import { signMessage } from 'react-native-web3-wallet';
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import loadFromLocalStorages from "../../loadFromLocalStorages"
import httpApi from "../../api"
import ShadowCard from "../../utils/shadowCard"
import LinearGradient from 'react-native-linear-gradient';
import AsyncStorage from '@react-native-async-storage/async-storage';

const LogIn = (props) => {
    const [loading, setLoading] = useState(false)
    const [password, setPassword] = useState("")
    const realm = useRealm();
    const { loadInitialData } = loadFromLocalStorages()
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const wallet = useQuery(schemaName.Wallet, wallet => {
        return wallet.filtered(`address == '${ethers.utils.getAddress(userInfo.Address)}'`);
    })[0];


    sendLogin = async () => {
        if (!password) return
        try {
            setLoading(true)
            if (!wallet) {
                setLoading(false)
                Toast.info("当前钱包不存在，请切换其他账号")
                return
            }
            const sign = await signMessage(
                wallet.keystore,
                password,
                httpApi.message,
            )
            const login = await httpApi.login({
                signature: sign,
                message: httpApi.message
            })
            if (login.code == 20) {
                props.setIsLogin(false)
                realm.write(() => {
                    userInfo.Token = login.data.Token
                });
                console.log(userInfo.Token, "111111111111111")
                console.log(login.data.Token, "111111111111111")
                await AsyncStorage.setItem("token", login.data.Token)
                props.navigation.navigate('chat')
                await loadInitialData()
            }
        } catch (error) {
            Toast.info(error?.message)
        }
        setLoading(false)
    }
    return (
        <View style={styles.page}>
            <View style={styles.boxLogo}>
                <Image style={styles.logo} source={require('../../assets/logo.png')}></Image>
            </View>
            <View style={styles.form}>
                <Text style={styles.label}>密码</Text>
                <TextInput
                    style={styles.textInput}
                    onChangeText={text => setPassword(text)}
                    value={password}
                    placeholder="密码"
                />
            </View>
            <View style={styles.footerButton}>
                <ShadowCard style={styles.button}>
                    <LinearGradient
                        colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                        start={{ x: 0.25, y: 0.25 }}
                        end={{ x: 0.75, y: 0.75 }}
                        style={[styles.linearGradient]}>
                        <TouchableOpacity type="primary" disabled={loading} style={[styles.button]} onPress={sendLogin}>
                            <>
                                {loading ? <ActivityIndicator /> : ""}
                                <Text style={styles.ButtonText}>登录</Text>
                            </>
                        </TouchableOpacity>
                    </LinearGradient>
                </ShadowCard>
            </View>
            <Text style={styles.other} onPress={() => { props.navigation.navigate('mineSwitchAccount') }}>切换其他账号</Text>
        </View>
    )
}

const mapStateToProps = state => {
    return {
        Wallet: state.wallet.Wallet,
        app: state.app
    }
}

export default connect(mapStateToProps, { asyncLogin, setIsLogin })(LogIn)


const styles = StyleSheet.create({
    page: {
        flex: 1,
        paddingHorizontal: pTx(35),
    },
    boxLogo: {
        paddingVertical: pTx(50),
        flexDirection: 'row',
        justifyContent: "center",
    },
    logo: {
        width: pTx(100),
        height: pTx(100),
        alignItems: "center",
        justifyContent: "center",
    },
    form: {
        marginTop: pTx(16),
    },
    label: {
        fontSize: pTx(15),
    },
    textInput: {
        marginTop: pTx(10),
        marginLeft: 0,
        paddingLeft: pTx(16),
        height: pTx(47),
        fontSize: pTx(16),
        backgroundColor: "rgba(255, 255, 255, 1)",
        borderWidth: 0,
        borderRadius: 6,
        overflow: "hidden",
        justifyContent: "center"
    },
    footerButton: {
        paddingTop: pTx(30),
        alignItems: "center"
    },
    linearGradient: {
        borderRadius: 6
    },
    button: {
        width: pTx(303),
        height: pTx(50),
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
    },
    ButtonText: {
        color: "rgba(10, 12, 20, 1)",
        fontSize: pTx(14),
        fontWeight: 'bold'
    },
    other: {
        paddingTop: pTx(20),
        textAlign: 'right'
    }
})